package labox.innovation.status;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.net.InetAddress;
import java.net.Socket;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Map.Entry;

import javolution.util.FastComparator;
import javolution.util.FastTable;
import labox.innovation.config.Config;
import labox.innovation.gameserver.Announcements;
import labox.innovation.gameserver.GameTimeController;
import labox.innovation.gameserver.GmListTable;
import labox.innovation.gameserver.LoginServerThread;
import labox.innovation.gameserver.Shutdown;
import labox.innovation.gameserver.ThreadPoolManager;
import labox.innovation.gameserver.cache.HtmCache;
import labox.innovation.gameserver.datatables.CharNameTable;
import labox.innovation.gameserver.datatables.ItemTable;
import labox.innovation.gameserver.datatables.SkillTable;
import labox.innovation.gameserver.datatables.TeleportLocationTable;
import labox.innovation.gameserver.handler.AdminCommandHandler;
import labox.innovation.gameserver.handler.IAdminCommandHandler;
import labox.innovation.gameserver.instancemanager.QuestManager;
import labox.innovation.gameserver.model.FuzeWorld;
import labox.innovation.gameserver.model.L2ItemInstance;
import labox.innovation.gameserver.model.L2Object;
import labox.innovation.gameserver.model.Punish;
import labox.innovation.gameserver.model.actor.L2Character;
import labox.innovation.gameserver.model.actor.L2Npc;
import labox.innovation.gameserver.model.actor.L2Summon;
import labox.innovation.gameserver.model.actor.instance.FuzeMonsterInstance;
import labox.innovation.gameserver.model.actor.instance.FuzePcInstance;
import labox.innovation.gameserver.model.actor.instance.FuzePcInstance.PlayerQuestValues;
import labox.innovation.gameserver.model.itemcontainer.Inventory;
import labox.innovation.gameserver.model.quest.dataset.JQuestXMLParse;
import labox.innovation.gameserver.network.SystemMessageId;
import labox.innovation.gameserver.network.clientpackets.Say2;
import labox.innovation.gameserver.network.serverpackets.CharInfo;
import labox.innovation.gameserver.network.serverpackets.CreatureSay;
import labox.innovation.gameserver.network.serverpackets.InventoryUpdate;
import labox.innovation.gameserver.network.serverpackets.SystemMessage;
import labox.innovation.gameserver.network.serverpackets.UserInfo;
import labox.innovation.gameserver.taskmanager.DecayTaskManager;

public class GameStatusThread extends Thread {
	//private static final Logger _log = Logger.getLogger(AdminTeleport.class.getName());

	private Socket _cSocket;

	private PrintWriter _print;

	private BufferedReader _read;

	private int _uptime;

	private void telnetOutput(int type, String text) {
		if (Config.DEVELOPER) {
			if (type == 1)
				System.out.println("TELNET | " + text);
			else if (type == 2)
				System.out.print("TELNET | " + text);
			else if (type == 3)
				System.out.print(text);
			else if (type == 4)
				System.out.println(text);
			else
				System.out.println("TELNET | " + text);
		} else {
			//only print output if the message is rejected
			if (type == 5)
				System.out.println("TELNET | " + text);
		}
	}

	private boolean isValidIP(Socket client) {
		boolean result = false;
		InetAddress ClientIP = client.getInetAddress();

		// convert IP to String, and compare with list
		String clientStringIP = ClientIP.getHostAddress();

		telnetOutput(1, "Connection from: " + clientStringIP);

		// read and loop thru list of IPs, compare with newIP
		if (Config.DEVELOPER)
			telnetOutput(2, "");

		InputStream telnetIS = null;
		try {
			Properties telnetSettings = new Properties();
			telnetIS = new FileInputStream(new File(Config.TELNET_FILE));
			telnetSettings.load(telnetIS);

			String HostList = telnetSettings.getProperty("ListOfHosts", "127.0.0.1,localhost");

			if (Config.DEVELOPER)
				telnetOutput(3, "Comparing ip to list...");

			// compare
			String ipToCompare = null;
			for (String ip : HostList.split(",")) {
				if (!result) {
					ipToCompare = InetAddress.getByName(ip).getHostAddress();
					if (clientStringIP.equals(ipToCompare))
						result = true;
					if (Config.DEVELOPER)
						telnetOutput(3, clientStringIP + " = " + ipToCompare + "(" + ip + ") = " + result + "\n");
				}
			}
		} catch (IOException e) {
			if (Config.DEVELOPER)
				telnetOutput(4, "");
			telnetOutput(1, "Error: " + e);
		} finally {
			try {
				telnetIS.close();
			} catch (Exception e) {
			}
		}

		if (Config.DEVELOPER)
			telnetOutput(4, "Allow IP: " + result);
		return result;
	}

	public GameStatusThread(Socket client, int uptime, String StatusPW) throws IOException {
		_cSocket = client;
		_uptime = uptime;

		_print = new PrintWriter(_cSocket.getOutputStream());
		_read = new BufferedReader(new InputStreamReader(_cSocket.getInputStream()));

		if (isValidIP(client)) {
			telnetOutput(1, client.getInetAddress().getHostAddress() + " accepted.");
			_print.println("Welcome To Innovation Telnet Session.");
			_print.println("Please Insert Your Password!");
			_print.print("Password: ");
			_print.flush();
			String tmpLine = _read.readLine();
			if (tmpLine == null) {
				_print.println("Error.");
				_print.println("Disconnected...");
				_print.flush();
				_cSocket.close();
			} else {
				if (tmpLine.compareTo(StatusPW) != 0) {
					_print.println("Incorrect Password!");
					_print.println("Disconnected...");
					_print.flush();
					_cSocket.close();
				} else {
					_print.println("Password Correct!");
					_print.println("[Innovation Game Server]");
					_print.print("");
					_print.flush();
					start();
				}
			}
		} else {
			telnetOutput(5, "Connection attempt from " + client.getInetAddress().getHostAddress() + " rejected.");
			_cSocket.close();
		}
	}

	/**
	 * 新的 命令处理方式
	 * 
	 * @param command
	 */
	void handleNewCommands(String command, PrintWriter printBf) {

		if (command.startsWith("char_info")) {

			String[] cmds = command.split(" ");
			if (cmds.length < 2) {
				//				printBf.println("char_info命令格式不对, char_info 角色名 或 角色id");
				printBf.println("char_info format is wrong, char_info <player's name or player's UID>");
				return;
			}

			long uid = -1;
			try {

				uid = Long.parseLong(cmds[1]);

			} catch (Exception e) {
				uid = CharNameTable.getInstance().getIdByName(cmds[1]);
			}

			if (uid == -1) {
				//				printBf.println("角色名 或 角色uid错误");
				printBf.println("plyaer's name is wrong or player's UID is wrong");
				return;
			}

			getPlayerInfo(printBf, uid);

		} else if (command.startsWith("char_bag")) { //角色背包

			String[] cmds = command.split(" ");
			if (cmds.length < 2) {
				//				printBf.println("char_bag命令格式不对, char_bag 角色名 或 角色id");
				printBf.println("char_bag fromat is wrong, char_bag <player's name or player's UID>");
				return;
			}

			long uid = -1;
			try {

				uid = Long.parseLong(cmds[1]);

			} catch (Exception e) {
				uid = CharNameTable.getInstance().getIdByName(cmds[1]);
			}

			if (uid == -1) {
				//				printBf.println("角色名 或 角色uid错误");
				printBf.println("plyaer's name is wrong or player's UID is wrong");
				return;
			}

			getPlayerBagInfo(printBf, uid);

		} else if (command.startsWith("char_quest")) { //角色人物

			String[] cmds = command.split(" ");
			if (cmds.length < 2) {
				//				printBf.println("char_quest命令格式不对, char_quest 角色名 或 角色id");
				printBf.println("char_quest format is wrong, char_quest  <player's name or player's UID>");
				return;
			}

			long uid = -1;
			try {

				uid = Long.parseLong(cmds[1]);

			} catch (Exception e) {
				uid = CharNameTable.getInstance().getIdByName(cmds[1]);
			}

			if (uid == -1) {
				//				printBf.println("角色名 或 角色uid错误");
				printBf.println("plyaer's name is wrong or player's UID is wrong");
				return;
			}

			getPlayerQuestInfo(printBf, uid);
		} else {
			IAdminCommandHandler commandHandler = AdminCommandHandler.getInstance().getAdminCommandHandler(command);
			if (commandHandler != null) {
				if (commandHandler.useAdminCommand(command, null)) {
					printBf.println("command sucess");
				} else {
					printBf.println("command error");
				}
			} else {
				printBf.println("command no find!");
			}
		}

	}// end handleNewCommands

	/**
	 * 获得角色的任务信息
	 * 
	 * @param printBf
	 * @param uid
	 */
	void getPlayerQuestInfo(PrintWriter printBf, long uid) {

		FuzePcInstance target = FuzeWorld.getInstance().getPlayer(uid);
		if (target == null) {
			//			printBf.println("角色不在线 或 没有指定的角色");
			printBf.println("player is not OnLine or player is not exist");
			return;
		}

		List<PlayerQuestValues> quests = target.getQuestValues();
		if (quests == null || quests.size() <= 0) {

			//			printBf.println( " 角色没有接任何任务 " );
			printBf.println(" player have no Quests");
			return;

		}

		//		printBf.println( "角色任务列表:" );
		printBf.println("player'sQuests:");
		for (PlayerQuestValues qt : quests) {
			printBf.println(qt.getName());
		}

	}

	/**
	 * 获得角色背包信息
	 * 
	 * @param printBf
	 * @param uid
	 */
	void getPlayerBagInfo(PrintWriter printBf, long uid) {

		FuzePcInstance target = FuzeWorld.getInstance().getPlayer(uid);
		if (target == null) {
			//			printBf.println("角色不在线 或 没有指定的角色");
			printBf.println("player is not OnLine or player is not exist");
			return;
		}

		L2ItemInstance[] items = target.getInventory().getItems();
		printBf.println("BagNums:" + items.length);
		if (items != null && items.length > 0) {
			//			printBf.println("背包数据:");
			printBf.println("bag's data:");
		}

		for (L2ItemInstance temp : items) {

			//			printBf.println("物品uid:" + temp.getObjectId() + " 物品名:" + temp.getName() + " 拥有者id:" + temp.getOwnerId() );
			//			printBf.println("物品是否装备:" + ( temp.isEquipable()?"已装备":"未装备" ) );
			//			printBf.println("物品数量:" + temp.getCount() );

			printBf.println("Item's uid:" + temp.getObjectId() + " Item Name:" + temp.getName() + " Owner id:" + temp.getOwnerId());
			printBf.println("isEquiped:" + (temp.isEquipable() ? "true" : "false"));
			printBf.println("Item Nums:" + temp.getCount());

		}

		items = target.getWarehouse().getItems();
		printBf.println("WareNums:" + items.length);
		if (items != null && items.length > 0) {
			//			printBf.println("仓库数据:");
			printBf.println("warehourse:");
		}

		for (L2ItemInstance temp : items) {
			//			printBf.println("物品uid:" + temp.getObjectId() + " 物品名:" + temp.getName() + " 拥有者id:" + temp.getOwnerId() );
			//			printBf.println("物品数量:" + temp.getCount() );

			printBf.println("Item's uid:" + temp.getObjectId() + " Item Name:" + temp.getName() + " Owner id:" + temp.getOwnerId());
			printBf.println("Item Nums:" + temp.getCount());

		}

	}// end getPlayerBagInfo

	/**
	 * 获得 角色信息
	 * 
	 * @param printBf
	 * @param uid
	 */
	void getPlayerInfo(PrintWriter printBf, long uid) {

		FuzePcInstance target = FuzeWorld.getInstance().getPlayer(uid);
		if (target == null) {
			//			printBf.println("角色不在线 或 没有指定的角色");
			printBf.println("player is not OnLine or player is not exist");
			return;
		}
		printBf.println("player name:" + target.getName());
		printBf.println("player uid:" + target.getObjectId());
		printBf.println("player Current HP:" + target.getCurrentHp());
		printBf.println("player Current MP:" + target.getCurrentMp());
		printBf.println("player Max HP:" + target.getMaxHp());
		printBf.println("player Max MP:" + target.getMaxMp());
		printBf.println("player level:" + target.getLevel());
		printBf.println("player Race:" + target.getRace().getName());
		printBf.println("player sex:" + target.getAppearance().getSex().getName());
		printBf.println("player class:" + target.getClassId().getName());
		printBf.println("player Practice:" + target.getPracticeId().getName());
		printBf.println("player Practice Thought:" + target.getPracticeId().getThought());
		printBf.println("player clan:" + (target.getClan() == null ? "none" : target.getClan().getName()));
		printBf.println("player Karma:" + target.getKarma());
		printBf.println("player NextLevelNeedExperience:" + target.getNextLevelNeedExperience());
		printBf.println("player Current Exp:" + target.getExp());
		printBf.println("player STR:" + target.getSTR());
		printBf.println("player DEX:" + target.getDEX());
		printBf.println("player INT:" + target.getINT());
		printBf.println("player MEN:" + target.getMEN());
		printBf.println("player CON:" + target.getCON());
		printBf.println("player power attack:" + target.getMinPAtk() + "-" + target.getMaxPAtk());
		printBf.println("player magic attack:" + target.getMinMAtk() + "-" + target.getMaxMAtk());
		printBf.println("player power def:" + target.getPDef() + " magic def:" + target.getMDef());
		printBf.println("player accuracy:" + target.getAccuracy());
		printBf.println("player EvasionRate:" + target.getEvasionRate());
		printBf.println("player Critical:" + target.getCriticalHit());
		printBf.println("player Bleed:" + target.getBleed());
		printBf.println("player BleedVuln:" + target.getBleedVuln());
		printBf.println("player Posion:" + target.getPosion());
		printBf.println("player PoisonVuln:" + target.getPoisonVuln());
		printBf.println("player Stun:" + target.getStun());
		printBf.println("player StunVuln:" + target.getStunVuln());
		printBf.println("player Root:" + target.getRoot());
		printBf.println("player RootVuln:" + target.getRootVuln());
		printBf.println("player Movement:" + target.getMovement());
		printBf.println("player MovementVuln:" + target.getMovementVuln());
		printBf.println("player Confusion:" + target.getConfusion());
		printBf.println("player ConfusionVuln:" + target.getConfusionVuln());
		printBf.println("player Sleep:" + target.getSleep());
		printBf.println("player SleepVuln:" + target.getSleepVuln());

	}// end 

	@Override
	public void run() {
		String _usrCommand = "";
		try {
			while (_usrCommand.compareTo("quit") != 0 && _usrCommand.compareTo("exit") != 0) {
				_usrCommand = _read.readLine();
				if (_usrCommand == null) {
					_cSocket.close();
					break;
				}

				if (_usrCommand.equals("help")) {
					_print.println("The following is a list of all available commands: ");
					_print.println("help                - shows this help.");
					_print.println("status              - displays basic server statistics.");
					_print.println("performance         - shows server performance statistics.");
					_print.println("forcegc             - forced garbage collection.");
					_print.println("purge               - removes finished threads from thread pools.");
					_print.println("memusage            - displays memory amounts in JVM.");
					_print.println("announce <text>     - announces <text> in game.");
					_print.println("msg <uid> <text>   - Sends a whisper to char <nick> with <text>.");
					_print.println("gmchat <text>       - Sends a message to all GMs with <text>.");
					_print.println("gmlist              - lists all gms online.");
					_print.println("admin_kick                - admin_kick player <name> from server.");
					_print.println("shutdown <time>     - shuts down server in <time> seconds.");
					_print.println("restart <time>      - restarts down server in <time> seconds.");
					_print.println("abort               - aborts shutdown/restart.");
					_print.println("give <player> <itemid> <amount>");
					_print.println("enchant <player> <itemType> <enchant> (itemType: 1 - Helmet, 2 - Chest, 3 - Gloves, 4 - Feet, 5 - Legs, 6 - Right Hand, 7 - Left Hand, 8 - Left Ear, 9 - Right Ear , 10 - Left Finger, 11 - Right Finger, 12- Necklace, 13 - Underwear, 14 - Back, 15 - Belt, 0 - No Enchant)");
					_print.println("extlist             - list all loaded extension classes");
					_print.println("extreload <name>    - reload and initializes the named extension or all if used without argument");
					_print.println("extinit <name>      - initilizes the named extension or all if used without argument");
					_print.println("extunload <name>    - unload the named extension or all if used without argument");
					_print.println("debug <cmd>         - executes the debug command (see 'help debug').");
					_print.println("jail <player> [time]");
					_print.println("unjail <player>");
					_print.println("quit                - closes telnet session.");
					_print.println("all gm cmd player'name can not numbers");
					_print.println("admin_teleportto <player name or player UID > <secen id> <x y>  - teleport");
					_print.println("admin_teleport_character <player name or player UID> <target player name or player UID> - teleport_character");
					_print.println("admin_ban_char <acc>  - ban acc");
					_print.println("admin_unban_char <acc>  - unban acc ");
					_print.println("admin_setinvul <player name or player UID>  - invul ");
					_print.println("char_info <player or playerId>  - character info");
					_print.println("char_quest <player or playerId> - character quest");
					_print.println("char_bag <player or playerId >   -character bag");
					_print.println("admin_reload_announcements   -reload announcements");
					_print.println("admin_giveitem  <player name or player uid> <itemid> [itemNums]");
					_print.println("admin_addexp  <player name or player uid> <expNums> ");
				} else if (_usrCommand.equals("help debug")) {
					_print.println("The following is a list of all available debug commands: ");
					_print.println("full                - Dumps complete debug information to an file (recommended)");
					_print.println("decay               - prints info about the DecayManager");
					_print.println("PacketTP            - prints info about the General Packet ThreadPool");
					_print.println("IOPacketTP          - prints info about the I/O Packet ThreadPool");
					_print.println("GeneralTP           - prints info about the General ThreadPool");
				} else if (_usrCommand.equals("status")) {
					_print.print(getServerStatus());
					_print.flush();
				} else if (_usrCommand.equals("forcegc")) {
					System.gc();
					StringBuilder sb = new StringBuilder();
					sb.append("RAM Used: " + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1048576)); // 1024 * 1024 = 1048576
					_print.println(sb.toString());
				} else if (_usrCommand.equals("performance")) {
					for (String line : ThreadPoolManager.getInstance().getStats()) {
						_print.println(line);
					}
					_print.flush();
				} else if (_usrCommand.equals("purge")) {
					ThreadPoolManager.getInstance().purge();
					_print.println("STATUS OF THREAD POOLS AFTER PURGE COMMAND:");
					_print.println("");
					for (String line : ThreadPoolManager.getInstance().getStats()) {
						_print.println(line);
					}
					_print.flush();
				} else if (_usrCommand.startsWith("memusage")) {
					double max = Runtime.getRuntime().maxMemory() / 1024; // maxMemory is the upper
					// limit the jvm can use
					double allocated = Runtime.getRuntime().totalMemory() / 1024; // totalMemory the
					// size of the
					// current
					// allocation pool
					double nonAllocated = max - allocated; // non allocated memory till jvm limit
					double cached = Runtime.getRuntime().freeMemory() / 1024; // freeMemory the
					// unused memory in
					// the allocation pool
					double used = allocated - cached; // really used memory
					double useable = max - used; // allocated, but non-used and non-allocated memory

					DecimalFormat df = new DecimalFormat(" (0.0000'%')");
					DecimalFormat df2 = new DecimalFormat(" # 'KB'");

					_print.println("+----");// ...
					_print.println("| Allowed Memory:" + df2.format(max));
					_print.println("|    |= Allocated Memory:" + df2.format(allocated) + df.format(allocated / max * 100));
					_print.println("|    |= Non-Allocated Memory:" + df2.format(nonAllocated) + df.format(nonAllocated / max * 100));
					_print.println("| Allocated Memory:" + df2.format(allocated));
					_print.println("|    |= Used Memory:" + df2.format(used) + df.format(used / max * 100));
					_print.println("|    |= Unused (cached) Memory:" + df2.format(cached) + df.format(cached / max * 100));
					_print.println("| Useable Memory:" + df2.format(useable) + df.format(useable / max * 100)); // ...
					_print.println("+----");
				} else if (_usrCommand.startsWith("announce")) {
					try {
						_usrCommand = _usrCommand.substring(9);
						Announcements.getInstance().announceToAll(_usrCommand);
						_print.println("Announcement Sent!");
					} catch (StringIndexOutOfBoundsException e) {
						_print.println("Please Enter Some Text To Announce!");
					}
				} else if (_usrCommand.startsWith("msg")) {
					try {
						String val = _usrCommand.substring(4);
						String[] st = val.split(" ");
						if (st.length < 2)
							return;
						long uid = Long.parseLong(st[0]);
						FuzePcInstance reciever = FuzeWorld.getInstance().getPlayer(uid);
						CreatureSay cs = new CreatureSay(0, Say2.SECRET_CHANNAL, "Telnet Priv", st[1]);
						if (reciever != null) {
							reciever.sendPacket(cs);
							_print.println("Telnet Priv->" + reciever.getName() + ": " + st[1]);
							_print.println("Message Sent!");
						} else {
							_print.println("Unable To Find Username: " + uid);
						}
					} catch (StringIndexOutOfBoundsException e) {
						_print.println("Please Enter Some Text!");
					}
				} else if (_usrCommand.startsWith("gmchat")) {
					try {
						_usrCommand = _usrCommand.substring(7);
						CreatureSay cs = new CreatureSay(0, Say2.COMMUNITY_CHANNAL, "Telnet GM Broadcast from " + _cSocket.getInetAddress().getHostAddress(), _usrCommand);
						GmListTable.broadcastToGMs(cs);
						_print.println("Your Message Has Been Sent To " + getOnlineGMS() + " GM(s).");
					} catch (StringIndexOutOfBoundsException e) {
						_print.println("Please Enter Some Text To Announce!");
					}
				} else if (_usrCommand.equals("gmlist")) {
					int igm = 0;
					String gmList = "";

					for (String player : GmListTable.getInstance().getAllGmNames(true)) {
						gmList = gmList + ", " + player;
						igm++;
					}
					_print.println("There are currently " + igm + " GM(s) online...");
					if (!gmList.isEmpty())
						_print.println(gmList);
				}
				/*else if (_usrCommand.startsWith("unblock")).
				 {
				 try
				 {
				 _usrCommand = _usrCommand.substring(8);
				 if (LoginServer.getInstance().unblockIp(_usrCommand))
				 {
				 _log.warning("IP removed via TELNET by host: " + _csocket.getInetAddress().getHostAddress());
				 _print.println("The IP " + _usrCommand + " has been removed from the hack protection list!");
				 }
				 else
				 {
				 _print.println("IP not found in hack protection list...");
				 }
				 //TODO: with packet
				 }
				 catch (StringIndexOutOfBoundsException e)
				 {
				 _print.println("Please Enter the IP to Unblock!");
				 }
				 }*/
				else if (_usrCommand.startsWith("admin_kick")) {
					try {
						_usrCommand = _usrCommand.substring(11);
						FuzePcInstance player = FuzeWorld.getInstance().getPlayer(Long.parseLong(_usrCommand));
						if (player != null) {
							player.sendMessage("you kicked by gm!");
							player.getClient().closeNow();
							_print.println("Player kicked");
						}
					} catch (Exception e) {
						_print.println("Please enter player uid to kick");
					}
				} else if (_usrCommand.startsWith("shutdown")) {
					try {
						int val = Integer.parseInt(_usrCommand.substring(9));
						Shutdown.getInstance().startTelnetShutdown(_cSocket.getInetAddress().getHostAddress(), val, false);
						_print.println("Server Will Shutdown In " + val + " Seconds!");
						_print.println("Type \"abort\" To Abort Shutdown!");
					} catch (StringIndexOutOfBoundsException e) {
						_print.println("Please Enter * amount of seconds to shutdown!");
					} catch (Exception NumberFormatException) {
						_print.println("Numbers Only!");
					}
				} else if (_usrCommand.startsWith("restart")) {
					try {
						int val = Integer.parseInt(_usrCommand.substring(8));
						Shutdown.getInstance().startTelnetShutdown(_cSocket.getInetAddress().getHostAddress(), val, true);
						_print.println("Server Will Restart In " + val + " Seconds!");
						_print.println("Type \"abort\" To Abort Restart!");
					} catch (StringIndexOutOfBoundsException e) {
						_print.println("Please Enter * amount of seconds to restart!");
					} catch (Exception NumberFormatException) {
						_print.println("Numbers Only!");
					}
				} else if (_usrCommand.startsWith("abort")) {
					Shutdown.getInstance().telnetAbort(_cSocket.getInetAddress().getHostAddress());
					_print.println("OK! - Shutdown/Restart Aborted.");
				} else if (_usrCommand.equals("quit")) { /* Do Nothing :p - Just here to save us from the "Command Not Understood" Text */
				} else if (_usrCommand.startsWith("give")) {
					StringTokenizer st = new StringTokenizer(_usrCommand.substring(5));

					try {
						FuzePcInstance player = FuzeWorld.getInstance().getPlayer(Integer.parseInt(st.nextToken()));
						int itemId = Integer.parseInt(st.nextToken());
						int amount = Integer.parseInt(st.nextToken());

						if (player != null) {
							L2ItemInstance item = player.getInventory().addItem("Status-Give", itemId, amount, null, null);
							InventoryUpdate iu = new InventoryUpdate();
							iu.addItem(item);
							player.sendPacket(iu);
							SystemMessage sm = new SystemMessage(SystemMessageId.YOU_PICKED_UP_S1_S2);
							sm.addItemName(itemId);
							sm.addItemNumber(amount);
							player.sendPacket(sm);
							_print.println("ok");
							//							GMAudit.auditGMAction("Telnet Admin", "Give Item", player.getName(), "item: " + itemId + " amount: " + amount);
						}
					} catch (Exception e) {

					}
				} else if (_usrCommand.startsWith("enchant")) {
					StringTokenizer st = new StringTokenizer(_usrCommand.substring(8), " ");
					int enchant = 0, itemType = 0;

					try {
						FuzePcInstance player = FuzeWorld.getInstance().getPlayer(Integer.parseInt(st.nextToken()));
						itemType = Integer.parseInt(st.nextToken());
						enchant = Integer.parseInt(st.nextToken());

						switch (itemType) {
						case 1:
							itemType = Inventory.PAPERDOLL_HEAD;
							break;
						case 2:
							itemType = Inventory.PAPERDOLL_CHEST;
							break;
						case 4:
							itemType = Inventory.PAPERDOLL_FEET;
							break;
						case 5:
							itemType = Inventory.PAPERDOLL_LEGS;
							break;
						case 10:
							itemType = Inventory.PAPERDOLL_LFINGER;
							break;
						case 11:
							itemType = Inventory.PAPERDOLL_RFINGER;
							break;
						case 12:
							itemType = Inventory.PAPERDOLL_NECK;
							break;
						default:
							itemType = 0;
						}

						if (enchant > 65535)
							enchant = 65535;
						else if (enchant < 0)
							enchant = 0;

						boolean success = false;

						if (player != null && itemType > 0) {
							success = setEnchant(player, enchant, itemType);
							if (success)
								_print.println("Item enchanted successfully.");
						} else if (!success)
							_print.println("Item failed to enchant.");
					} catch (Exception e) {

					}
				} else if (_usrCommand.startsWith("jail")) {
					StringTokenizer st = new StringTokenizer(_usrCommand.substring(5));
					try {
						String playerName = st.nextToken();
						final FuzePcInstance playerObj = FuzeWorld.getInstance().getPlayer(Long.parseLong(playerName));
						final int delay = Integer.parseInt(st.nextToken());

						if (playerObj != null) {
							playerObj.getPunish().setPunishLevel(Punish.PunishLevel.GMJAIL, delay);	
							_print.println("Character " + playerObj.getName() + " jailed for " + (delay > 0 ? delay + " minutes." : "ever!"));
						} else
							jailOfflinePlayer(playerName, delay);
					} catch (Exception nsee) {
						_print.println("Specify a player UID and time.error:" + nsee.getMessage());
					}
				} else if (_usrCommand.startsWith("unjail")) {
					StringTokenizer st = new StringTokenizer(_usrCommand.substring(7));
					try {
						String playerUid = st.nextToken();
						final FuzePcInstance playerObj = FuzeWorld.getInstance().getPlayer(Long.parseLong(playerUid));

						if (playerObj != null) {
							playerObj.getPunish().setPunishLevel(Punish.PunishLevel.NONE, 0);	
							_print.println("Character " + playerObj.getName() + " removed from jail");
						} else
							unjailOfflinePlayer(playerUid);
					} catch (Exception e) {
						_print.println("Specify a player UID.error:" + e.getMessage());
					}
				} else if (_usrCommand.startsWith("debug") && _usrCommand.length() > 6) {
					StringTokenizer st = new StringTokenizer(_usrCommand.substring(6));
					FileOutputStream fos = null;
					OutputStreamWriter out = null;
					try {
						String dbg = st.nextToken();

						if (dbg.equals("decay")) {
							_print.print(DecayTaskManager.getInstance().toString());
						} else if (dbg.equals("ai")) {
							/*
							 _print.println("AITaskManagerStats");
							 for(String line : AITaskManager.getInstance().getStats())
							 {
							 _print.println(line);
							 }
							 */
						} else if (dbg.equals("aiflush")) {
							//AITaskManager.getInstance().flush();
						} else if (dbg.equals("IOPacketTP")) {
							String str = ThreadPoolManager.getInstance().getIOPacketStats();
							_print.println(str);
							int i = 0;
							File f = new File("./log/StackTrace-IOPacketTP-" + i + ".txt");
							while (f.exists()) {
								i++;
								f = new File("./log/StackTrace-IOPacketTP-" + i + ".txt");
							}
							f.getParentFile().mkdirs();
							fos = new FileOutputStream(f);
							out = new OutputStreamWriter(fos, "UTF-8");
							out.write(str);
						} else if (dbg.equals("full")) {
							this.debugAll();
						}
					} catch (Exception e) {
					} finally {
						try {
							out.close();
						} catch (Exception e) {
						}

						try {
							fos.close();
						} catch (Exception e) {
						}
					}

				} else if (_usrCommand.startsWith("reload")) {
					StringTokenizer st = new StringTokenizer(_usrCommand.substring(7));
					try {
						String type = st.nextToken();

						if (type.equals("skill")) {
							_print.print("Reloading skills... ");
							SkillTable.getInstance().reload();
							_print.print("done\n");
						} else if (type.equals("npc")) {
							if (!st.hasMoreElements()) {
								_print.print("Reloading npc templates... ");
								// NpcTemplateTable.getInstance().reloadAllNpc();
								QuestManager.getInstance().reloadAllQuests();
								JQuestXMLParse.getInstance().parseExcelTemplet(new File(Config.DATAPACK_ROOT, "/data/questScriptTemplet.xml"));
								_print.print("done\n");
							} else {
								String npcId = st.nextToken();
								_print.print("Reloading npc templates... " + npcId);
								// NpcTemplateTable.getInstance().reloadAllNpc();
								QuestManager.getInstance().reload(Integer.parseInt(npcId));
								_print.print("done\n");
							}
						} else if (type.equals("html")) {
							_print.print("Reloading html cache... ");
							HtmCache.getInstance().reload();
							_print.print("done\n");
						} else if (type.equals("item")) {
							_print.print("Reloading item templates... ");
							ItemTable.getInstance().reload();
							_print.print("done\n");
						} else if (type.equals("zone")) {
							_print.print("Reloading zone tables... ");
							//TODO: ZONETODO reload zones using telnet ZoneManager.getInstance().reload();
							_print.print("done\n");
						} else if (type.equals("teleports")) {
							_print.print("Reloading telport location table... ");
							TeleportLocationTable.getInstance().reloadAll();
							_print.print("done\n");
						} else if (type.equals("spawns")) {
							_print.print("Reloading spawns... ");
							FuzeWorld.getInstance().deleteVisibleNpcSpawns();
							// NpcTemplateTable.getInstance().reloadAllNpc();
							// SpawnTable.getInstance().reloadAll();
							_print.print("done\n");
						}

					} catch (Exception e) {
					}
				} else {

					handleNewCommands(_usrCommand, _print);

				}
				_print.print("");
				_print.flush();
			}
			if (!_cSocket.isClosed()) {
				_print.println("Bye Bye!");
				_print.flush();
				_cSocket.close();
			}
			telnetOutput(1, "Connection from " + _cSocket.getInetAddress().getHostAddress() + " was closed by client.");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private boolean setEnchant(FuzePcInstance activeChar, int ench, int armorType) {
		// now we need to find the equipped weapon of the targeted character...
		int curEnchant = 0; // display purposes only
		L2ItemInstance itemInstance = null;

		// only attempt to enchant if there is a weapon equipped
		L2ItemInstance parmorInstance = activeChar.getInventory().getPaperdollItem(armorType);
		if (parmorInstance != null && parmorInstance.getLocationSlot() == armorType) {
			itemInstance = parmorInstance;
		}

		if (itemInstance != null) {
			curEnchant = itemInstance.getEnchantLevel();

			// set enchant value
			activeChar.getInventory().unEquipItemInSlotAndRecord(armorType);
			itemInstance.setEnchantLevel(ench);
			activeChar.getInventory().equipItemAndRecord(itemInstance);

			// send packets
			InventoryUpdate iu = new InventoryUpdate();
			iu.addModifiedItem(itemInstance);
			activeChar.sendPacket(iu);
			activeChar.broadcastPacket(new CharInfo(activeChar));
			activeChar.sendPacket(new UserInfo(activeChar));
			//			activeChar.broadcastPacket(new ExBrExtraUserInfo(activeChar));

			// informations
			activeChar.sendMessage("Changed enchantment of " + activeChar.getName() + "'s " + itemInstance.getItem().getName() + " from " + curEnchant + " to " + ench + ".");
			activeChar.sendMessage("Admin has changed the enchantment of your " + itemInstance.getItem().getName() + " from " + curEnchant + " to " + ench + ".");

			// log
			//			GMAudit.auditGMAction("TelnetAdministrator", "enchant", activeChar.getName(), itemInstance.getItem().getName() + "(" + itemInstance.getObjectId() + ")" + " from " + curEnchant + " to " + ench);
			return true;
		}
		return false;
	}

	private void jailOfflinePlayer(String name, int delay) {
		//		Connection con = null;
		//		try {
		//			con = L2DatabaseFactory.getInstance().getConnection();
		//
		//			PreparedStatement statement = con.prepareStatement("UPDATE characters SET x=?, y=?, z=?, punish_level=?, punish_timer=? WHERE char_name=?");
		//			statement.setInt(1, -114356);
		//			statement.setInt(2, -249645);
		//			statement.setInt(3, -2984);
		//			statement.setInt(4, FuzePcInstance.PunishLevel.JAIL.value());
		//			statement.setLong(5, delay * 60000L);
		//			statement.setString(6, name);
		//
		//			statement.execute();
		//			int count = statement.getUpdateCount();
		//			statement.close();
		//
		//			if (count == 0)
		//				_print.println("Character not found!");
		//			else
		//				_print.println("Character " + name + " jailed for " + (delay > 0 ? delay + " minutes." : "ever!"));
		//		} catch (SQLException se) {
		//			_print.println("SQLException while jailing player");
		//			if (Config.DEBUG)
		//				se.printStackTrace();
		//		} finally {
		//			try {
		//				con.close();
		//			} catch (Exception e) {
		//			}
		//		}
	}

	private void unjailOfflinePlayer(String name) {
		//		Connection con = null;
		//		try {
		//			con = L2DatabaseFactory.getInstance().getConnection();
		//
		//			PreparedStatement statement = con.prepareStatement("UPDATE characters SET x=?, y=?, z=?, punish_level=?, punish_timer=? WHERE char_name=?");
		//			statement.setInt(1, 17836);
		//			statement.setInt(2, 170178);
		//			statement.setInt(3, -3507);
		//			statement.setInt(4, 0);
		//			statement.setLong(5, 0);
		//			statement.setString(6, name);
		//
		//			statement.execute();
		//			int count = statement.getUpdateCount();
		//			statement.close();
		//
		//			if (count == 0)
		//				_print.println("Character not found!");
		//			else
		//				_print.println("Character " + name + " set free.");
		//		} catch (SQLException se) {
		//			_print.println("SQLException while jailing player");
		//			if (Config.DEBUG)
		//				se.printStackTrace();
		//		} finally {
		//			try {
		//				con.close();
		//			} catch (Exception e) {
		//			}
		//		}
	}

	private int getOnlineGMS() {
		return GmListTable.getInstance().getAllGms(true).size();
	}

	private String getUptime(int time) {
		int uptime = (int) System.currentTimeMillis() - time;
		uptime = uptime / 1000;
		int h = uptime / 3600;
		int m = (uptime - (h * 3600)) / 60;
		int s = ((uptime - (h * 3600)) - (m * 60));
		return h + "hrs " + m + "mins " + s + "secs";
	}

	private String gameTime() {
		int t = GameTimeController.getInstance().getGameTime();
		int h = t / 60;
		int m = t % 60;
		SimpleDateFormat format = new SimpleDateFormat("H:mm");
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, h);
		cal.set(Calendar.MINUTE, m);
		return format.format(cal.getTime());
	}

	@SuppressWarnings("deprecation")
	public String getServerStatus() {
		int playerCount = 0, objectCount = 0;
		int max = LoginServerThread.getInstance().getMaxPlayer();

		playerCount = FuzeWorld.getInstance().getAllPlayersCount();
		objectCount = FuzeWorld.getInstance().getAllVisibleObjectsCount();

		int itemCount = 0;
		int itemVoidCount = 0;
		int monsterCount = 0;
		int minionCount = 0;
		int minionsGroupCount = 0;
		int npcCount = 0;
		int charCount = 0;
		int pcCount = 0;
		int detachedCount = 0;
		int summonCount = 0;
		int AICount = 0;
		int disableAI = 0;

		Collection<L2Object> objs = FuzeWorld.getInstance().getAllObjects().values();

		for (L2Object obj : objs) {
			if (obj == null)
				continue;
			if (obj instanceof L2ItemInstance) {
				if (((L2ItemInstance) obj).getLocation() == L2ItemInstance.ItemLocation.VOID)
					itemVoidCount++;
				else
					itemCount++;
			} else if (obj instanceof L2Character) {
				charCount++;
				if (((L2Character) obj).hasAI()) {
					AICount++;
					if (((L2Character) obj).isCoreAIDisabled()) {
						disableAI++;
					}
				}

				if (obj instanceof L2Npc) {
					npcCount++;
					if (obj instanceof FuzeMonsterInstance) {
						monsterCount++;
						minionCount += ((FuzeMonsterInstance) obj).getTotalSpawnedMinionsInstances();
						minionsGroupCount += ((FuzeMonsterInstance) obj).getTotalSpawnedMinionsGroups();
					}
				} else if (obj instanceof FuzePcInstance) {
					pcCount++;
					if (((FuzePcInstance) obj).getClient().isDetached())
						detachedCount++;
				} else if (obj instanceof L2Summon) {
					summonCount++;
				}
			}
		}

		StringBuilder sb = new StringBuilder();
		sb.append("Server Status: ");
		sb.append("\r\n  --->  Player Count: " + playerCount + "/" + max);
		sb.append("\r\n  ---> Offline Count: " + detachedCount + "/" + playerCount);
		sb.append("\r\n  +-->  Object Count: " + objectCount);
		sb.append("\r\n  +-->      AI Count: " + AICount);
		sb.append("\r\n  +->DisableAI Count: " + disableAI);
		sb.append("\r\n  +.... L2Item(Void): " + itemVoidCount);
		sb.append("\r\n  +.......... L2Item: " + itemCount);
		sb.append("\r\n  +....... L2Monster: " + monsterCount);
		sb.append("\r\n  +......... Minions: " + minionCount);
		sb.append("\r\n  +.. Minions Groups: " + minionsGroupCount);
		sb.append("\r\n  +........... L2Npc: " + npcCount);
		sb.append("\r\n  +............ L2Pc: " + pcCount);
		sb.append("\r\n  +........ L2Summon: " + summonCount);
		sb.append("\r\n  +.......... L2Char: " + charCount);
		sb.append("\r\n  --->   Ingame Time: " + gameTime());
		sb.append("\r\n  ---> Server Uptime: " + getUptime(_uptime));
		sb.append("\r\n  --->      GM Count: " + getOnlineGMS());
		sb.append("\r\n  --->       Threads: " + Thread.activeCount());
		sb.append("\r\n  RAM Used: " + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1048576)); // 1024 * 1024 = 1048576
		sb.append("\r\n");

		return sb.toString();
	}

	@SuppressWarnings("serial")
	public void debugAll() throws IOException {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");

		StringBuilder sb = new StringBuilder();
		sb.append(sdf.format(cal.getTime()));
		sb.append("\n\nL2J Server Version: " + Config.SERVER_VERSION);
		sb.append("\nDP Revision: " + Config.DATAPACK_VERSION);
		sb.append("\n\n");
		sb.append(this.getServerStatus());
		sb.append("\n\n");
		sb.append("\n## Java Platform Information ##");
		sb.append("\nJava Runtime Name: " + System.getProperty("java.runtime.name"));
		sb.append("\nJava Version: " + System.getProperty("java.version"));
		sb.append("\nJava Class Version: " + System.getProperty("java.class.version"));
		sb.append('\n');
		sb.append("\n## Virtual Machine Information ##");
		sb.append("\nVM Name: " + System.getProperty("java.vm.name"));
		sb.append("\nVM Version: " + System.getProperty("java.vm.version"));
		sb.append("\nVM Vendor: " + System.getProperty("java.vm.vendor"));
		sb.append("\nVM Info: " + System.getProperty("java.vm.info"));
		sb.append('\n');
		sb.append("\n## OS Information ##");
		sb.append("\nName: " + System.getProperty("os.name"));
		sb.append("\nArchiteture: " + System.getProperty("os.arch"));
		sb.append("\nVersion: " + System.getProperty("os.version"));
		sb.append('\n');
		sb.append("\n## Runtime Information ##");
		sb.append("\nCPU Count: " + Runtime.getRuntime().availableProcessors());
		sb.append("\nCurrent Free Heap Size: " + (Runtime.getRuntime().freeMemory() / 1024 / 1024) + " mb");
		sb.append("\nCurrent Heap Size: " + (Runtime.getRuntime().totalMemory() / 1024 / 1024) + " mb");
		sb.append("\nMaximum Heap Size: " + (Runtime.getRuntime().maxMemory() / 1024 / 1024) + " mb");

		sb.append('\n');
		sb.append("\n## Class Path Information ##\n");
		String cp = System.getProperty("java.class.path");
		String[] libs = cp.split(File.pathSeparator);
		for (String lib : libs) {
			sb.append(lib);
			sb.append('\n');
		}

		sb.append('\n');
		sb.append("## Threads Information ##\n");
		Map<Thread, StackTraceElement[]> allThread = Thread.getAllStackTraces();

		FastTable<Entry<Thread, StackTraceElement[]>> entries = new FastTable<Entry<Thread, StackTraceElement[]>>();
		entries.setValueComparator(new FastComparator<Entry<Thread, StackTraceElement[]>>() {

			@Override
			public boolean areEqual(Entry<Thread, StackTraceElement[]> e1, Entry<Thread, StackTraceElement[]> e2) {
				return e1.getKey().getName().equals(e2.getKey().getName());
			}

			@Override
			public int compare(Entry<Thread, StackTraceElement[]> e1, Entry<Thread, StackTraceElement[]> e2) {
				return e1.getKey().getName().compareTo(e2.getKey().getName());
			}

			@Override
			public int hashCodeOf(Entry<Thread, StackTraceElement[]> e) {
				return e.hashCode();
			}

		});
		entries.addAll(allThread.entrySet());
		entries.sort();
		for (Entry<Thread, StackTraceElement[]> entry : entries) {
			StackTraceElement[] stes = entry.getValue();
			Thread t = entry.getKey();
			sb.append("--------------\n");
			sb.append(t.toString() + " (" + t.getId() + ")\n");
			sb.append("State: " + t.getState() + '\n');
			sb.append("isAlive: " + t.isAlive() + " | isDaemon: " + t.isDaemon() + " | isInterrupted: " + t.isInterrupted() + '\n');
			sb.append('\n');
			for (StackTraceElement ste : stes) {
				sb.append(ste.toString());
				sb.append('\n');
			}
			sb.append('\n');
		}

		sb.append('\n');
		this.checkForDeadlocks(sb);

		sb.append("\n\n## Thread Pool Manager Statistics ##\n");
		for (String line : ThreadPoolManager.getInstance().getStats()) {
			sb.append(line);
			sb.append('\n');
		}

		int i = 0;
		File f = new File("./log/Debug-" + i + ".txt");
		while (f.exists()) {
			i++;
			f = new File("./log/Debug-" + i + ".txt");
		}
		f.getParentFile().mkdirs();
		FileOutputStream fos = new FileOutputStream(f);
		OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8");
		out.write(sb.toString());
		out.flush();
		out.close();
		fos.close();

		_print.println("Debug output saved to log/" + f.getName());
		_print.flush();
	}

	private void checkForDeadlocks(StringBuilder sb) {
		ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
		long[] ids = findDeadlockedThreads(mbean);
		if (ids != null && ids.length > 0) {
			Thread[] threads = new Thread[ids.length];
			for (int i = 0; i < threads.length; i++) {
				threads[i] = findMatchingThread(mbean.getThreadInfo(ids[i]));
			}
			sb.append("Deadlocked Threads:\n");
			sb.append("-------------------\n");
			for (Thread thread : threads) {
				System.err.println(thread);
				for (StackTraceElement ste : thread.getStackTrace()) {
					sb.append("\t" + ste);
					sb.append('\n');
				}
			}
		}
	}

	private long[] findDeadlockedThreads(ThreadMXBean mbean) {
		// JDK 1.5 only supports the findMonitorDeadlockedThreads()
		// method, so you need to comment out the following three lines
		if (mbean.isSynchronizerUsageSupported()) {
			return mbean.findDeadlockedThreads();
		} else {
			return mbean.findMonitorDeadlockedThreads();
		}
	}

	private Thread findMatchingThread(ThreadInfo inf) {
		for (Thread thread : Thread.getAllStackTraces().keySet()) {
			if (thread.getId() == inf.getThreadId()) {
				return thread;
			}
		}
		throw new IllegalStateException("Deadlocked Thread not found");
	}
}
